package logger

/*
封装日志
*/
import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

//Log log入口
var Log *zap.Logger
var SLog *zap.SugaredLogger

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func getLogWriter() zapcore.WriteSyncer {
	exeName := filepath.Base(os.Args[0])
	exeParts := strings.Split(exeName, ".")
	logName := exeName
	if len(exeParts) > 0 {
		logName = exeParts[0]
	}
	fmt.Println("log--------", logName)
	lumberJackLogger := &lumberjack.Logger{
		Filename:   "../slogs/" + logName + ".log",
		MaxSize:    1,
		MaxBackups: 5,
		MaxAge:     7,
		Compress:   false,
	}
	return zapcore.AddSync(lumberJackLogger)
}

func init() {
	writeSyncer := getLogWriter()
	encoder := getEncoder()
	// High-priority output should also go to standard error, and low-priority
	// output should also go to standard out.
	//consoleDebugging := zapcore.Lock(os.Stdout)

	// for human operators.
	//consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())

	var allCore []zapcore.Core
	coreChild := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
	allCore = append(allCore, coreChild)

	consoleDebugging := zapcore.Lock(os.Stdout)
	coreChild = zapcore.NewCore(encoder, consoleDebugging, zapcore.DebugLevel)
	allCore = append(allCore, coreChild)

	core := zapcore.NewTee(allCore...)

	// From a zapcore.Core, it's easy to construct a Logger.
	Log = zap.New(core).WithOptions(zap.AddCaller())
	Log.Warn("----------******************-iotbase-a connection to endless world-************----------zw------")
	SLog = Log.Sugar()
}
